package com.example.administrator.swredeem.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;

import com.example.administrator.swredeem.R;
import com.example.administrator.swredeem.adapter.Adapting;
import com.example.administrator.swredeem.appBase.Config;
import com.example.administrator.swredeem.net.HttpXutils;
import com.example.administrator.swredeem.net.MyCallback;
import com.example.administrator.swredeem.utils.ShowImagesDialog;
import com.example.administrator.swredeem.utils.Utils;
import com.example.administrator.swredeem.view.recyclerview.BaseQuickAdapter;
import com.example.administrator.swredeem.view.recyclerview.RecyclerItemClickSupport;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.guoqi.actionsheet.ActionSheet;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;

import org.json.JSONArray;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class KaihuSqActivity extends AppCompatActivity implements View.OnClickListener, ActionSheet.OnActionSheetSelected, TakePhoto.TakeResultListener, InvokeListener, RecyclerItemClickSupport.OnItemClickListener, RecyclerItemClickSupport.OnItemLongClickListener {

    @BindView(R.id.ll_fwlx)
    LinearLayout llFwlx;
    @BindView(R.id.kaihushenqing)
    TextView kaihushenqing;
    @BindView(R.id.khsq)
    TextView khsq;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_lxfs)
    EditText etLxfs;
    @BindView(R.id.et_sfzh)
    EditText etSfzh;
    @BindView(R.id.et_khh)
    EditText etKhh;
    @BindView(R.id.et_rqbh)
    EditText etRqbh;
    @BindView(R.id.tx_szqy)
    TextView txSzqy;
    @BindView(R.id.ll_szqy)
    LinearLayout llSzqy;
    @BindView(R.id.et_xxdz)
    EditText etXxdz;
    @BindView(R.id.recyclerview_tzd)
    RecyclerView recyclerviewTzd;
    @BindView(R.id.recyclerview_rqb)
    RecyclerView recyclerviewRqb;
    @BindView(R.id.recyclerview_sfz)
    RecyclerView recyclerviewSfz;
    @BindView(R.id.recyclerview_ht)
    RecyclerView recyclerviewHt;
    private InvokeParam invokeParam;
    private TakePhoto takePhoto;
    private Uri imageUri;
    private String TAG = KaihuSqActivity.class.getName();
    private List<Object> tzdlistimg = new ArrayList<>();//燃气开户通知单
    private List<Object> rqblistimg = new ArrayList<>();//燃气表
    private List<Object> sfzlistimg = new ArrayList<>();//房屋产权人身份证
    private List<Object> htlistimg = new ArrayList<>();//房产证或购房合同
    private Adapting adapterimgtzd, adapterimgrqb, adapterimgsfz, adapterimght;
    //是谁在使用相机 目前是按照顺序排列
    private int isUsing = 1;

    private OptionsPickerView pickerView;
    private List list;
    private int MaxImgsum = 5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kaihu_sq);
        ButterKnife.bind(this);
        getTakePhoto().onCreate(savedInstanceState);
        initdata();


        init();


    }

    private void initdata() {
        list = new ArrayList();
        llFwlx.setOnClickListener(this);
        llSzqy.setOnClickListener(this);
        initRecyclerview();
    }

    private void initRecyclerview() {
        //初始化适配器
        adapterimgtzd = new Adapting(tzdlistimg);
        adapterimgrqb = new Adapting(rqblistimg);
        adapterimgsfz = new Adapting(sfzlistimg);
        adapterimght = new Adapting(htlistimg);

        //添加默认数据
        tzdlistimg.add(R.drawable.addimg);
        rqblistimg.add(R.drawable.addimg);
        sfzlistimg.add(R.drawable.addimg);
        htlistimg.add(R.drawable.addimg);

        //通知单
        recyclerviewTzd.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerviewTzd.hasFixedSize();
        recyclerviewTzd.setAdapter(adapterimgtzd);
        RecyclerItemClickSupport.addTo(recyclerviewTzd).setOnItemClickListener(this);
        RecyclerItemClickSupport.addTo(recyclerviewTzd).setOnItemLongClickListener(this);

        //燃气表
        recyclerviewRqb.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerviewRqb.hasFixedSize();
        recyclerviewRqb.setAdapter(adapterimgrqb);
        RecyclerItemClickSupport.addTo(recyclerviewRqb).setOnItemClickListener(this);
        RecyclerItemClickSupport.addTo(recyclerviewRqb).setOnItemLongClickListener(this);

        //身份证
        recyclerviewSfz.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerviewSfz.hasFixedSize();
        recyclerviewSfz.setAdapter(adapterimgsfz);
        RecyclerItemClickSupport.addTo(recyclerviewSfz).setOnItemClickListener(this);
        RecyclerItemClickSupport.addTo(recyclerviewSfz).setOnItemLongClickListener(this);

        //合同
        recyclerviewHt.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerviewHt.hasFixedSize();
        recyclerviewHt.setAdapter(adapterimght);
        RecyclerItemClickSupport.addTo(recyclerviewHt).setOnItemClickListener(this);
        RecyclerItemClickSupport.addTo(recyclerviewHt).setOnItemLongClickListener(this);


    }

    private void init() {
        //获取屏幕密度
        getDeviceDensity();
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        imageUri = Uri.fromFile(file);
    }

    public void goSubmit(View v) {
        String str = "[{'img':'1'},{'img':'1'}]";
        Map<String, String> map = new HashMap<>();
        map.put("userno","1600240291");//户号
        map.put("username", etName.getText().toString());//姓名
        map.put("region", "1");//区域
        map.put("addr", etXxdz.getText().toString());//地址
        map.put("certnum", etSfzh.getText().toString());//身份证号
        map.put("mobile", etLxfs.getText().toString());//联系方式
        map.put("meterno", "1");//表号
        map.put("opencustimgs", netData(tzdlistimg));//开户申请图片字符串
        map.put("meterimgs", netData(sfzlistimg));//身份证图片字符串JSONArray
        map.put("certimgs", netData(rqblistimg));//表具图片字符串JSONArray
        map.put("contimgs", netData(htlistimg));//合同或房产证图片字符串JSONArray
        map.put("operator", "sysadmin");//操作员ID（登录的操作员的ID，测试时传入“sysadmin”）必填
        map.put("deviceid", "001");//设备编号（测试时任意传入）必填
        map.put("source", "1");//来源（1手持设备APP，2微信公众号，APP恒定传入1）
        getdata(map);
    }

    public void getdata(Map map) {

        HttpXutils.getPost(Config.KHZLTj, map, new MyCallback() {

            @Override
            public void onSuccess(String result) {
                Log.d("TAG", "onSuccess: " + result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("TAG", "onError: " + ex.getMessage() + isOnCallback);
                Toast.makeText(KaihuSqActivity.this, "网络错误，请联系管理员", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onClick(View v) {
        list.clear();
        switch (v.getId()) {
            case R.id.ll_fwlx:
                list.add("开户申请");
                list.add("过户申请");
                ShowDig(kaihushenqing);
                break;
            case R.id.ll_szqy:
                list.add("武昌");
                list.add("汉口");
                list.add("汉阳");
                ShowDig(txSzqy);
                break;
        }
    }

    //弹窗显示拍照
    @Override
    public void onClick(int whichButton) {
        switch (whichButton) {
            case ActionSheet.CHOOSE_PICTURE:
                //相册
                if (isUsing == 1) {
                    takePhoto.onPickMultiple(MaxImgsum - tzdlistimg.size() + 1);
                } else if (isUsing == 2) {
                    takePhoto.onPickMultiple(MaxImgsum - rqblistimg.size() + 1);
                } else if (isUsing == 3) {
                    takePhoto.onPickMultiple(MaxImgsum - sfzlistimg.size() + 1);
                } else if (isUsing == 4) {
                    takePhoto.onPickMultiple(MaxImgsum - htlistimg.size() + 1);
                }
                break;
            case ActionSheet.TAKE_PICTURE:
                //拍照
                takePhoto.onPickFromCaptureWithCrop(imageUri, getCropOptions(800, 800));
                break;
            case ActionSheet.CANCEL:
                //取消
                break;
        }
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void takeSuccess(TResult result) {
        Log.i(TAG, "takeSuccess：" + result.getImage().getOriginalPath());
        int size = result.getImages().size();
        for (int i = 0; i < size; i++) {
            if (isUsing == 1) {
                tzdlistimg.add(0, result.getImages().get(i).getOriginalPath());
            } else if (isUsing == 2) {
                rqblistimg.add(0, result.getImages().get(i).getOriginalPath());
            } else if (isUsing == 3) {
                sfzlistimg.add(0, result.getImages().get(i).getOriginalPath());
            } else if (isUsing == 4) {
                htlistimg.add(0, result.getImages().get(i).getOriginalPath());
            }
        }
        Log.d(TAG, "takeSuccess: " + tzdlistimg.size());
        updataRe();

    }

    @Override
    public void takeFail(TResult result, String msg) {
        Log.i(TAG, "takeFail:" + msg);
    }

    @Override
    public void takeCancel() {

    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    //裁剪
    private CropOptions getCropOptions(int width, int height) {
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(width).setAspectY(height);
        builder.setOutputX(width).setOutputY(height);
        return builder.create();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }


    //单项选择弹出框
    public void ShowDig(final TextView textView) {
        pickerView = new OptionsPickerView.Builder(KaihuSqActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                // 获取选中项的文本
                String data = list.get(options1).toString();
                textView.setText(data);
                Log.d(TAG, "onOptionsSelect: " + data);
            }
        }).build(); // 生成OptionsPickerView
        pickerView.setPicker(list); // 一级选择器
        pickerView.show(); // 显示

    }


    @Override
    public void onItemClicked(RecyclerView recyclerView, int position, View v) {
        Log.d(TAG, "onItemClicked: " + position + recyclerView.getId());

        switch (recyclerView.getId()) {
            case R.id.recyclerview_tzd:
                isUsing = 1;
                myReOnItemCilck(tzdlistimg, position);
                break;
            case R.id.recyclerview_rqb:
                isUsing = 2;
                myReOnItemCilck(rqblistimg, position);
                break;
            case R.id.recyclerview_sfz:
                isUsing = 3;
                myReOnItemCilck(sfzlistimg, position);
                break;
            case R.id.recyclerview_ht:
                isUsing = 4;
                myReOnItemCilck(htlistimg, position);
                break;
        }


    }

    @Override
    public void onItemLongClicked(RecyclerView recyclerView, int position, View v) {
        switch (recyclerView.getId()) {
            case R.id.recyclerview_tzd:
                isUsing = 1;
                showNormalDialog(tzdlistimg, position);
                break;
            case R.id.recyclerview_rqb:
                isUsing = 2;
                showNormalDialog(rqblistimg, position);
                break;
            case R.id.recyclerview_sfz:
                isUsing = 3;
                showNormalDialog(sfzlistimg, position);
                break;
            case R.id.recyclerview_ht:
                isUsing = 4;
                showNormalDialog(htlistimg, position);
                break;
        }

    }

    /**
     * 获取当前设备的屏幕密度等基本参数
     */
    protected void getDeviceDensity() {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        Config.EXACT_SCREEN_HEIGHT = metrics.heightPixels;
        Config.EXACT_SCREEN_WIDTH = metrics.widthPixels;
    }

    private void showNormalDialog(final List listimgg, final int position) {
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog = new AlertDialog.Builder(this);
        normalDialog.setMessage("确定删除该图片？");
        normalDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                listimgg.remove(position + 1);
                updataRe();
            }
        });

        // 显示
        normalDialog.show();
    }


    /**
     * @param imglist  哪个ImgList
     * @param position
     */
    private void myReOnItemCilck(List imglist, int position) {
        //展示的img集合
        List<String> list = new ArrayList<>();
        if (imglist.size() < 6 && position == imglist.size() - 1) {
            //拍照相册选择框
            ActionSheet.showSheet(this, this, null);
        } else if (imglist.size() == 6 && position == imglist.size() - 1) {
            Toast.makeText(this, "最多只能上传5张", Toast.LENGTH_SHORT).show();
        } else {
            for (Object s : imglist) {
                list.add(s + "");
            }
            new ShowImagesDialog(KaihuSqActivity.this, list, position).show();
        }
    }


    //更新适配器数据
    private void updataRe() {
        if (isUsing == 1) {
            adapterimgtzd.setNewData(tzdlistimg);
        } else if (isUsing == 2) {
            adapterimgrqb.setNewData(rqblistimg);
        } else if (isUsing == 3) {
            adapterimgsfz.setNewData(sfzlistimg);
        } else if (isUsing == 4) {
            adapterimght.setNewData(htlistimg);
        }
    }


    private String netData(List<Object> lists){
        if(lists==null&&lists.size()<0){
            return null;
        }
        List<Map> jsonArray = new ArrayList<>();
        lists.remove(lists.size()-1);
        Log.d(TAG, "netData: "+lists.size());
        for (Object list : lists){
            String imageStr = Utils.GetImageStr(String.valueOf(list));
            Map<String, String> map = new HashMap<>();
            Log.d(TAG, "goSubmit: "+imageStr);
            map.put("img",imageStr);
            jsonArray.add(map);
        }
        Gson gson = new Gson();
        return gson.toJson(jsonArray);
    }
}
